package com.example.prom.ok.y2023.work.channelPrice;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.example.prom.listener.ExcelListener;
import com.example.prom.ok.y2023.work.maxmind.MaxMindIpReaderVO;
import com.example.prom.ok.y2023.work.maxmind.MaxMindResultDTO;
import com.example.prom.ok.y2023.work.maxmind.RegionVO2;
import com.example.prom.strategy.excel.CustomCellStyleStrategy;
import com.example.prom.strategy.excel.CustomColumnWidthStrategy;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.alibaba.excel.EasyExcelFactory.read;
import static com.alibaba.excel.EasyExcelFactory.write;

@RestController
@Slf4j
public class MsgChannelPriceHandler {

    @RequestMapping("write")
    public void writeExcel_1(HttpServletResponse response) throws IOException {
//        write(writeFileName, MaxMindIpReaderVO.class).sheet().head(MaxMindIpReaderVO.class)
//                .registerWriteHandler(new CustomColumnWidthStrategy())
//                .registerWriteHandler(new CustomCellStyleStrategy()).doWrite(new ArrayList<>());
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName= URLEncoder.encode("测试","UTF-8").replaceAll("\\+","%20");
        response.setHeader("Content-disposition","attachment;filename*=utf-8''"+fileName+".xlsx");
        EasyExcel.write(response.getOutputStream(),ChannelPriceVO.class).sheet("模板")
                .registerWriteHandler(new CustomColumnWidthStrategy())
                .registerWriteHandler(new CustomCellStyleStrategy()).doWrite(new ArrayList<>());

    }



    public static void main(String[] args) throws Exception{
        writeExcel(new ArrayList<>());
    }
//    public static void main(String[] args) {
////        MaxMindResultDTO maxMindResultDTO = validateIP("91.207.27.76");
////        System.out.println(JSON.toJSONString(maxMindResultDTO));
//        List<MaxMindIpReader> maxMindIpReaders = readExcel();
//        for (MaxMindIpReader maxMindIpReader : maxMindIpReaders) {
//            String applicable_regions = maxMindIpReader.getApplicable_regions();
//            String[] split = applicable_regions
//                    .replace("'","").replace("[","")
//                    .replace("]","").split(",");
//            if (split.length > 1){
//                log.info("maxMindIpReader.applicable_regions.length > 1 :{}", JSON.toJSONString(maxMindIpReader));
//            }
//
//        }
//    }


    public static List<ChannelPriceVO> readExcel() {
        String fileName = "C:\\Users\\hp\\Desktop\\tentcentPrice.xlsx";
        ExcelListener<ChannelPriceVO> excelListener = new ExcelListener<>();
        read(fileName, ChannelPriceVO.class, excelListener).sheet().doRead();
        List<ChannelPriceVO> dataList = excelListener.getDataList();
        return dataList;
    }

    public static List<ChannelPriceVO2> readExcel2() {
        String fileName = "C:\\Users\\hp\\Desktop\\tentcentPrice.xlsx";
        ExcelListener<ChannelPriceVO2> excelListener = new ExcelListener<>();
        read(fileName, ChannelPriceVO2.class, excelListener).sheet("Sheet2").doRead();
        List<ChannelPriceVO2> dataList = excelListener.getDataList();
        return dataList;
    }

    public static void writeExcel(List<MaxMindIpReaderVO> writerList){
        String writeFileName = "D:\\dangwen\\maxmind_ipip_match_20230614_2.xlsx";
        write(writeFileName, MaxMindIpReaderVO.class).sheet().head(MaxMindIpReaderVO.class)
                .registerWriteHandler(new CustomColumnWidthStrategy())
                .registerWriteHandler(new CustomCellStyleStrategy()).doWrite(writerList);
    }

    public static void writeExcel2(List<MaxMindIpReaderVO> writerList){
        String writeFileName = "C:\\Users\\hp\\Desktop\\ok\\maxmind_ipip_notMatch_20230614_2.xlsx";
        write(writeFileName, MaxMindIpReaderVO.class).sheet().head(MaxMindIpReaderVO.class)
                .registerWriteHandler(new CustomColumnWidthStrategy())
                .registerWriteHandler(new CustomCellStyleStrategy()).doWrite(writerList);
    }

    public static MaxMindResultDTO validateIP(String ip) {
        MaxMindResultDTO resultDTO = new MaxMindResultDTO();
        try {
            // A File object pointing to your GeoIP2 or GeoLite2 database
            File database = new File("C:\\Users\\hp\\Desktop\\ok\\work\\GeoIP2-City_20230613\\GeoIP2-City.mmdb");

// This creates the DatabaseReader object. To improve performance, reuse
// the object across lookups. The object is thread-safe.
            DatabaseReader reader = new DatabaseReader.Builder(database).build();

            InetAddress ipAddress = InetAddress.getByName(ip);

// Replace "city" with the appropriate method for your database, e.g.,
// "country".
            CityResponse response = reader.city(ipAddress);

            Country country = response.getCountry();
//        System.out.println(country.getIsoCode());            // 'US'
//        System.out.println(country.getName());               // 'United States'
//        System.out.println(country.getNames().get("zh-CN")); // '美国'

            Subdivision subdivision = response.getMostSpecificSubdivision();
//        System.out.println(subdivision.getName());    // 'Minnesota'
//        System.out.println(subdivision.getNames().get("zh-CN"));    // 'Minnesota'
//        System.out.println(subdivision.getIsoCode()); // 'MN'

            City city = response.getCity();
//        System.out.println(city.getName()); // 'Minneapolis'
//        System.out.println(city.getNames().get("zh-CN")); // 'Minneapolis'

            Postal postal = response.getPostal();
//        System.out.println(postal.getCode()); // '55455'

            Location location = response.getLocation();
//        System.out.println(location.getLatitude());  // 44.9733
//        System.out.println(location.getLongitude()); // -93.2323


            resultDTO.setCountryIsoCode(country.getIsoCode());
            resultDTO.setCountryNameEn(country.getName());
            resultDTO.setCountryNameZh(country.getNames().get("zh-CN"));
            resultDTO.setRegionIsoCode(subdivision.getIsoCode());
            resultDTO.setRegionNameEn(subdivision.getName());
            resultDTO.setRegionNameZh(subdivision.getNames().get("zh-CN"));
            resultDTO.setCityNameEn(city.getName());
            resultDTO.setCityNameZh(city.getNames().get("zh-CN"));
            resultDTO.setLatitude(location.getLatitude());
            resultDTO.setLongitude(location.getLongitude());

        } catch (Exception e){
            log.error("ip解析异常,ip:{}", ip, e);
            resultDTO.setRegionNameEn(e.getMessage());
            resultDTO.setRegionNameZh(e.getMessage());
        }
        return resultDTO;
    }
}
